﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices.Automation;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Printing;
using System.Windows.Shapes;

namespace TelerikWrappedControl
{
    public partial class CustomImageViewer : UserControl
    {
        public CustomImageViewer()
        {
            InitializeComponent();

            _imageViewer.ImageFailed += _imageViewer_ImageFailed;

            _imageViewer.MouseLeftButtonDown += _imageViewer_MouseLeftButtonDown;
        }


        void _imageViewer_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {
            if (Deployment.Current.Dispatcher.CheckAccess())
            {
                _imageViewer.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("noImage.png", UriKind.RelativeOrAbsolute));

            }
            else
            {
                var e1 = new ManualResetEvent(false);
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    _imageViewer.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("noImage.png", UriKind.RelativeOrAbsolute));

                    e1.Set();
                });
                e1.WaitOne();
            }
        }

        private string _codiceArticoloTemp;
        private string _codiceOrdine;
        private string _cliente;
        private string _quantita;
        private string _consegna;

        public void TryLoadImage(string codiceArticolo, string codiceOrdine, string cliente, string quantita, string consegna)
        {
            _codiceOrdine = codiceOrdine;
            _cliente = cliente;
            _quantita = quantita;
            _consegna = consegna;
            if (Deployment.Current.Dispatcher.CheckAccess())
            {
                _codiceArticoloTemp = codiceArticolo;
                tryLoadImage();
            }
            else
            {
                var e = new ManualResetEvent(false);
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    _codiceArticoloTemp = codiceArticolo;
                    tryLoadImage();

                    e.Set();
                });
                e.WaitOne();
            }
        }

        void tryLoadImage()
        {
            var path = GetImagePath(_codiceArticoloTemp);
            _imageViewer.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri(path, UriKind.Absolute));
          
        }

        void _imageViewer_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (Deployment.Current.Dispatcher.CheckAccess())
            {
                OpenImage();

            }
            else
            {
                var e1 = new ManualResetEvent(false);
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    OpenImage();
                    e1.Set();
                });

                e1.WaitOne();
            }

            //Dispatchers.Main.BeginInvoke(() =>
            //   {
            //       var filePath1 = GetCurrentImageFilePath();

            //       // if (!File.Exists(filePath1)) return;

            //       //var shell1 = AutomationFactory.CreateObject("WScript.Shell");
            //       //shell1.Run(filePath1);

            //       var shell1 = AutomationFactory.CreateObject("Shell.Application");

            //       shell1.ShellExecute(filePath1);

            //       //var shell = AutomationFactory.CreateObject(@"C:\Windows\System32\rundll32.exe");

            //       //shell.ShellExecute(@"C:\Windows\system32\shimgvw.dll,ImageView_Fullscreen " + filePath1);
            //   });


            //Microsoft.LightSwitch.Threading.Dispatchers.Main.BeginInvoke(() =>
            //{
            var filePath1 = GetImagePath(_codiceArticoloTemp);

            if (AutomationFactory.IsAvailable)
            {
                dynamic shell = AutomationFactory.CreateObject("Shell.Application");


                shell.ShellExecute(filePath1);

                //dynamic shell = AutomationFactory.CreateObject("Shell.Application");
                //string printFilePath = "\"" + downloadDocPath + "\"";
                //shell.ShellExecute(@"" + filePath1 + "", "", "", "print", 0);
            }
            else if (!System.Windows.Application.Current.IsRunningOutOfBrowser)
            {
                System.Windows.Browser.HtmlPage.Window.Navigate(new Uri(filePath1, UriKind.RelativeOrAbsolute), "_new");
            }
            else
            {
                throw new InvalidOperationException();
            }

            //});

        }
        private void OpenImage()
        {
            var filePath1 = GetImagePath(_codiceArticoloTemp);

            if (AutomationFactory.IsAvailable)
            {
                dynamic shell = AutomationFactory.CreateObject("Shell.Application");

                shell.ShellExecute(filePath1);
            }
            else if (!System.Windows.Application.Current.IsRunningOutOfBrowser)
            {
                System.Windows.Browser.HtmlPage.Window.Navigate(new Uri(filePath1, UriKind.RelativeOrAbsolute), "_new");
            }
            else
            {
                throw new InvalidOperationException();
            }
        }

        private void PrintImage()
        {
            PrintDocument pd = new PrintDocument();

            pd.Print(string.Empty);

            pd.PrintPage += new EventHandler<PrintPageEventArgs>(pd_PrintPage);

       //public MainPage() 
       //{ 
       //    InitializeComponent(); 
       //    pd.PrintPage += new EventHandler<PrintPageEventArgs>(pd_PrintPage); 
       //}

       //private void PrintButton_Click(object sender, RoutedEventArgs e) 
       //{ 
       //    pd.DocumentName = "My Map"; 
       //    // Open the print dialog. 
       //    pd.Print(); 
       //}

       //void pd_PrintPage(object sender, PrintPageEventArgs e) 
       //{ 
       //    // Set the UI element to print. 
       //    e.PageVisual = mapImage; 
       //}
        }

        void pd_PrintPage(object sender, PrintPageEventArgs args)
        {
            var MARGIN = 7;

            // Find the full size of the page 
            Size pageSize =
              new Size(args.PrintableArea.Width
              + args.PageMargins.Left + args.PageMargins.Right,
              args.PrintableArea.Height
              + args.PageMargins.Top + args.PageMargins.Bottom);

            // Get additional margins to bring the total to MARGIN (= 96) 
            Thickness additionalMargin = new Thickness
            {
                Left = Math.Max(0, MARGIN - args.PageMargins.Left),
                Top = Math.Max(0, MARGIN - args.PageMargins.Top),
                Right = Math.Max(0, MARGIN - args.PageMargins.Right),
                Bottom = Math.Max(0, MARGIN - args.PageMargins.Bottom)
            };

            // Find the area for display purposes 
            Size displayArea =
              new Size(args.PrintableArea.Width
              - additionalMargin.Left - additionalMargin.Right,
              args.PrintableArea.Height
              - additionalMargin.Top - additionalMargin.Bottom);

            var bitmap = _imageViewer.Source as System.Windows.Media.Imaging.BitmapImage;

            bool pageIsLandscape = displayArea.Width > displayArea.Height;
            bool imageIsLandscape = bitmap.PixelWidth > bitmap.PixelHeight;

            double displayAspectRatio = displayArea.Width / displayArea.Height;
            double imageAspectRatio = (double)bitmap.PixelWidth / bitmap.PixelHeight;

            double scaleX = Math.Min(1, imageAspectRatio / displayAspectRatio);
            double scaleY = Math.Min(1, displayAspectRatio / imageAspectRatio);

            // Calculate the transform matrix 
            MatrixTransform transform = new MatrixTransform();

            if (pageIsLandscape == imageIsLandscape)
            {
                // Pure scaling 
                transform.Matrix = new Matrix(scaleX, 0, 0, scaleY, 0, 0);
            }
            else
            {
                // Scaling with rotation 
                scaleX *= pageIsLandscape ? displayAspectRatio : 1 /
                  displayAspectRatio;
                scaleY *= pageIsLandscape ? displayAspectRatio : 1 /
                  displayAspectRatio;
                transform.Matrix = new Matrix(0, scaleX, -scaleY, 0, 0, 0);
            }

            Image image = new Image
            {
                Source = bitmap,
                Stretch = Stretch.Fill,
                Width = displayArea.Width,
                Height = displayArea.Height,
                RenderTransform = transform,
                RenderTransformOrigin = new Point(0.5, 0.5),
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment = VerticalAlignment.Center,
                Margin = additionalMargin,
            };

            //Border border = new Border
            //{
            //    Child = image,
            //};
            //args.PageVisual = border;

            var stackPanel = new StackPanel();
            var header = new TextBlock();
            header.VerticalAlignment = VerticalAlignment.Top;
            header.Text = string.Format("Cliente:{0}      Cod.Ord:{1}      Q.tà:{2}      Cons:{3}", _cliente, _codiceOrdine, _quantita, _consegna);
            stackPanel.Children.Add(header);
            stackPanel.Children.Add(image);
            args.PageVisual = stackPanel;

        }
        private string GetImagePath(string codiceArticolo)
        {
            var hostName = string.Empty;
            var port = 0;

            //Dispatchers.Main.Invoke(() =>
            //{
            hostName = System.Windows.Application.Current.Host.Source.DnsSafeHost;
            port = System.Windows.Application.Current.Host.Source.Port;
            //});

            //// better to keep this in a global config singleton
            //string hostName = Application.Current.Host.Source.Host;
            if (hostName.ToLower() != "localhost")
                if (port != 80)
                    hostName += ":" + port;

            return string.Format("http://{0}/Gestione11/Images/{1}.jpg", hostName, codiceArticolo);

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (Deployment.Current.Dispatcher.CheckAccess())
            {
                PrintImage();
            }
            else
            {
                var e1 = new ManualResetEvent(false);
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    PrintImage();
                    e1.Set();
                });

                e1.WaitOne();
            }
        }

    
    }
}
